<?php

namespace addons\shopro\controller;

use addons\shopro\exception\Exception;
use addons\shopro\model\Dispatch;
use addons\shopro\model\Richtext;
use addons\shopro\model\User;
use addons\shopro\model\UserAddress;
use app\admin\model\CatOrder;
use think\Db;

class CatsOrder extends Base
{
    protected $noNeedLogin = ['orders', 'signing', 'guide'];
    protected $noNeedRight = ['*'];

    public function orders()
    {
        $user = User::info();
        if (request()->isPost()) {
            $address_id = $this->request->post('address_id/d');//用户地址id
            $cat_id = $this->request->post('cat_id/d');//猫咪id
            $message = $this->request->post('message/s');//卖家留言
            $deduction_time = $this->request->post('deduction_time/s'); //扣款时间
            if(empty($deduction_time)){
                //自定义支付时间
                $deduction_time = strtotime('+3 day');
            }else{
                //支付
                $deduction_time = strtotime($deduction_time);
                if(!$deduction_time){
                    $this->error('扣款时间不正确');
                }
            }

            //$endtime = strtotime('+1 month');
            $endtime = strtotime('+7 day');
            if($endtime < $deduction_time){
                $this->error('扣款时间不能超过最近7天');
            }
            $deduction_day = date('d',$deduction_time);
            $deduction_time = date('Y-m-d 09:0:0',$deduction_time);

            $deduction_time = date('Y-m-d H:i:s',(time() + 60 * 20));

            if (empty($address_id)) {
                $this->error('用户地址不能为空!');
            }
            if (empty($cat_id)) {
                $this->error('下单猫咪不能为空!');
            }

            //存入到猫咪订单表,等待
            $user_address = (new UserAddress())->where('id', $address_id)->find();
            $address = $user_address->province_name . $user_address->city_name . $user_address->area_name . $user_address->address;

            $city_info = Db::name('baofu_area')->where('area_name',$user_address->city_name)->find();

            $csProvince = "0";          //收货人省份
            $csCity = $city_info == null ? '02' : $city_info['area_code'];             //收货人城市

            $cat_info = $this->getCatInfo($cat_id);
            $data['order_sn'] = date('YmdHis') . 'cats' . $user->id;
            $data['user_id'] = $user->id;
            $data['breed_name'] = $cat_info['name'];
            $data['age'] = $cat_info['age'];
            $data['cat_code'] = $cat_info['cat_code'];
            $data['image'] = $cat_info['image'];
            $data['consignee'] = $user_address['consignee'];
            $data['phone'] = $user_address['phone'];
            $data['address'] = $address;
            $data['cat_id'] = $cat_id;
            $data['score_amount'] = $cat_info['integral'];
            $data['total_amount'] = $cat_info['price'];
            $data['remark'] = $message;
            $data['total_cycle'] = $cat_info['total_cycle'];//总签约周期数
            $data['remaining_cycle'] = $cat_info['total_cycle'];//剩余签约周期数
            $data['month_money'] = bcdiv($cat_info['price'],$cat_info['total_cycle'],2);
            $data['createtime'] = time();

            $data['csProvince'] = $csProvince;
            $data['csCity'] = $csCity;
            $data['deduction_time'] = $deduction_time;
            $data['deduction_day'] = $deduction_day;
            $data['paytime'] = strtotime($deduction_day.' 9:0:0');
            $result = (new \app\admin\model\CatOrder())->insertGetId($data);//获得id
            $order_sn = $data['order_sn'];
            //订单信息
            //修改猫咪状态 为 已经领养
            \addons\shopro\model\Cats::where('id',$cat_id)->update(['type'=>0]);//猫咪改为已经签约
            //半个小时没有签约，自动取消
            // 订单创建后
            $data = [
                'user_id' => $user->id,
                'order_id' => $result,
            ];
            \think\Hook::listen('cats_order_create_after', $data);
            $this->success('签约成功', ['order_id' => $result,'order_sn' => $order_sn]);

        }

    }

    /**
     * 签约确认页接口
     * @return void
     */
    public function signing()
    {
        $cat_id = $this->request->post('cat_id/d');//猫咪id
        $address_id = $this->request->post('address_id/d');//地址id
        if (empty($cat_id)) {
            $this->error('猫咪信息不能为空!');
        }
        if (empty($address_id)) {
            $this->error('地址信息不能为空!');
        }
        $cat_info = $this->getCatInfo($cat_id);
        $cat_info['image'] = cdnurl($cat_info['image'], true);
        $cat_info['gender'] = $cat_info['gender'] == 1 ? '公' : '母';
        //物流模版
        $dispatch_info = (new Dispatch())->where('id', $cat_info['dispatch_ids'])->find();
        //某个模板针对不同地区的价格信息
        $dispatch_type_select = Db::name('shopro_dispatch_' . $dispatch_info['type'])->whereIn('id', $dispatch_info['type_ids'])->select();

        //快递
        $user_address = (new UserAddress())->where('id', $address_id)->find();

        $dispatch_price = 0;    //物流价格
        //筛选地区，在地区内增加响应的物流价格
        foreach ($dispatch_type_select as $value) {

            //省
            if ($value['province_ids'] == $user_address['province_id'] || strpos($value['province_ids'], (string)$user_address['province_id'])) {
                $dispatch_price += $value['first_price'];
            }
            //市
            if ($value['city_ids'] == $user_address['city_id'] || strpos($value['city_ids'], (string)$user_address['city_id'])) {
                $dispatch_price += $value['first_price'];
            }
            //区
            if ($value['area_ids'] == $user_address['area_id'] || strpos($value['area_ids'], (string)$user_address['area_id'])) {
                //首件价格,数据表是以元为单位
                $dispatch_price += $value['first_price'];
                //续件价格，这里购买猫咪数量都是一，暂时用不到，用到需要修改，这里没判断猫咪数量
//                if($value['additional_num'] && $value['additional_price']){
//                    $dispatch_price += $value['additional_num'] * $value['additional_price'];
//                }
            }

        }

        //喵咪价格
        $cat_info['price'] = $cat_info['price'] + $dispatch_price;
        $result['cat_info'] = $cat_info;
        $this->success('签约页', $result);
    }

    public function getCatInfo($cat_id)
    {
        return (new \addons\shopro\model\Cats())->where('id', $cat_id)
            ->field('id,name,age,gender,breed,image,cat_code,price,dispatch_type,dispatch_ids,integral,total_cycle')
            ->find();
    }

    /**
     * 周期付引导图文介绍
     * @return void
     */
    public function guide()
    {

        $richtext_guide = (new Richtext())->where('title', "周期付引导")->find();
        $result['info'] = $richtext_guide;
        $this->success('周期付引导', $result);
    }


    public function getCatOrderList()
    {
        $user = User::info();

//        new \app\admin\model\CatOrder()->where()
    }


    // 订单列表
    public function index()
    {
        $params = $this->request->post();
        $this->success('订单列表', self::getList($params));
    }

    public static function getList($params)
    {
        $user = User::info();
        extract($params);
        $page = $params['page'];
        $type = $params['type'];
        $where = [];
        switch ($type) {
            case 'all':
                break;
            case '0':
                $where['status'] = 0;
                break;
            case '1':
                $where['status'] = 1;
                break;
            case '2':
                $where['status'] = 2;
                break;
            case '3':
                $where['status'] = -2;
                break;
            case '4':
                $where['status'] = -1;
                break;
        }
        $data= CatOrder::where('user_id', $user->id)
            ->where($where)->order('id', 'desc')
            ->paginate(10, false, ['page' => $page]);
        foreach ($data as &$val){
          $val['gender']=\addons\shopro\model\Cats::where('id',$val['cat_id'])->value('gender');
          $val['gender']=$val['gender']==1 ? '公':'母';
        }

        return $data;
    }

    // 订单详情
    public function detail()
    {
        $params = $this->request->post();
        $user = User::info();
        $where['cat_order.id'] = $params['id'];
        $order = CatOrder::where('user_id', $user->id)->with('cat')->where($where)->find();
        if (!$order) {
            new Exception('订单不存在');
        }
        if(!empty($order['deduction_day']) && empty($order['repayment'])){
            $order['repayment'] = $order['deduction_day'];
        }

        $this->success('订单列表', $order);
    }

}